<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
    <el-breadcrumb-item>应用安装</el-breadcrumb-item>
  </el-breadcrumb>

  <el-table :data="appTableData" width="80%" ref="appTableRef" @selection-change="handleSelectionChange"
    :cell-class-name="tableCellClassName">
    <el-table-column prop="id" type="selection" width="55" />
    <el-table-column prop="appName" label="应用名" width="200"></el-table-column>
    <el-table-column prop="appIp" label="主机IP" width="220"></el-table-column>
    <el-table-column prop="username" label="username" width="120"></el-table-column>
    <el-table-column prop="password" label="password" width="120"></el-table-column>
    <el-table-column prop="appDockerPath" label="docker workspace"></el-table-column>
    <el-table-column prop="port" label="App Port" width="120"></el-table-column>
    <el-table-column prop="appFlag" label="App Status" width="120" :formatter="formatter">
    </el-table-column>
  </el-table>

  <el-dialog v-model="appDialogVisible" title="添加应用" width="30%" :close-on-click-modal="false">
    <el-form ref="appFormRef" :model="appform" label-width="80px" v-loading="fullscreenLoading">
      <el-form-item label="选择主机" prop="appIp">
        <el-select v-model="appform.appIp" placeholder="应用IP" value-key="id" clearable>
          <el-option v-for="item in typeOptions" :key="item.hostIp" :value="item.hostIp" :label="item.hostIp" />
        </el-select>
      </el-form-item>
      <el-form-item label="应用名称" prop="appName">
        <el-radio-group v-model="appform.appName">
          <el-radio v-for="item in appNames" :key="item.item_value" :label="item.item_name" />
        </el-radio-group>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="appDialogVisible = false">撤销</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-form>
  </el-dialog>

  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect">

    <div class="flex-grow" />
    <el-menu-item index="1" @click="addAppWin(row)">
      <el-icon>
        <UploadFilled />
      </el-icon>应用安装
    </el-menu-item>
    <el-menu-item index="2" @click="deleteAppRow()">
      <el-icon>
        <DeleteFilled />
      </el-icon>删除应用
    </el-menu-item>
  </el-menu>
</template>
 
<script>
import { ref, reactive, toRef } from 'vue';
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElMessage } from 'element-plus';

import axios from 'axios';
import global from '../components/Global.vue';

const state = reactive({
  color: "black"
});
export default {
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem
  },
  created() {
    this.loadAppTableData();
    this.loadIPSelectData();
  },
  data() {
    return {
      baseUrl: global.baseUrl,
      toolDelUrl: global.baseUrl + '/install/del/app',
      autoInstallUrl: global.baseUrl + '/install/autoInstall',
      listUrl: global.baseUrl + '/host/list',
      appListUrl: global.baseUrl + '/app/get/list/APP_TOOL',
    }
  },
  setup() {
    const typeOptions = [];
    const appNames = [{ "item_name": "mysql", "item_value": "mysql" }, { "item_name": "httpd", "item_value": "httpd" }];
    const appTableData = ref([
      {
        appName: 'mysql',
        appIp: '192.168.152.100',
        appFlag: 0
      }
    ]);

    const appform = ref({
      'appIp': '',
      'appName': ''
    });
    const appDialogVisible = ref(false);
    const appTableRef = ref({});
    const colorRef = toRef(state, "color");
    const formatter = (row, column, cellValue) => {
      //row每行的内容 column每一列的属性信息 cellValue单元格的值
      if (cellValue === 0) { //不包含值为 0 的情况 另做判断
        colorRef.value = "red";
        return 'X';
      } else if (cellValue === 1) { //cellValue会自动将0值过滤出来不展示 单独做判断
        colorRef.value = "green";
        return '✔';
      } else {
        colorRef.value = "black";
        return '-' //没有值时展示 --
      }
    };

    const fullscreenLoading = ref(false);

    const addAppWin = () => {
      appDialogVisible.value = true;
    };

    const submitForm = () => {
      //const formRef = this.$refs.appFormRef;
      console.info(appform.value);

      fullscreenLoading.value = true;
      var url = global.baseUrl + '/install/autoInstall';
      axios.put(url, appform.value, global.config)
        .then((response) => {
          console.info(response.data);
          //appTableData.value.push(response.data.data);
          appDialogVisible.value = false;
          fullscreenLoading.value = false;
          appTableData.value = response.data.data;
          ElMessage({
            message: '自动安装成功.',
            type: 'success',
          });
        })
        .catch((error) => {
          console.error(error);
          fullscreenLoading.value = false;
          ElMessage.error('自动安装失败.');
        });
    };

    return {
      appNames,
      typeOptions,
      appTableData,
      appTableRef,
      appform,
      appDialogVisible,
      submitForm,
      addAppWin,
      formatter,
      fullscreenLoading
    };
  },
  methods: {
    deleteAppRow() {
      const rows = this.$refs.appTableRef.getSelectionRows();
      if(rows.length==0){
        console.info("delete app rows: {}",rows ,rows.length==0 );
        this.$message({
          type: 'info',
          message: '请选择应用!!!'
        });
        return ;
      }

      let ids = [];
      rows.forEach(function (element) {
        ids.push(element.id);
      });

      this.$confirm('此操作将永久删除该应用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.request({
          url: this.toolDelUrl,
          method: "delete",
          headers: global.config,
          data: ids
        }).then(res => {
          console.info("批量删除返回" + res);
          this.$message({
            message: "删除成功",
            type: "success"
          })
          this.appTableData.forEach((v, i) => {
            //console.info("《 ids 》", ids, "《v》", v, i);
            ids.forEach((vv, ii) => {
              if (vv === v.id) {
                console.info(ii, "< vv , ii >", vv, v.id);
                this.appTableData.splice(i, 1);
              }
            });
          });
          this.$refs.appTableRef.clearSelection();
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    loadIPSelectData() {
      axios.get(this.listUrl)
        .then((response) => {
          console.log(response.data);
          this.typeOptions = response.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    loadAppTableData() {
      axios.get(this.appListUrl)
        .then((response) => {
          console.log(response.data);
          this.appTableData = response.data.data;
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }
};
</script>

<style>
.el-table {
  margin: 3px auto;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.example-showcase .el-loading-mask {
  z-index: 9;
}
</style>
  